package com.ruibo.modules.weixin.rest;

import cn.binarywang.wx.miniapp.api.WxMaJsapiService;
import cn.binarywang.wx.miniapp.api.impl.WxMaJsapiServiceImpl;
import com.ruibo.annotation.AnonymousAccess;
import com.ruibo.modules.weixin.service.dto.RegionCodeQueryCriteria;
import com.ruibo.utils.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

/**
 * @description:
 * @author: 孙 峰
 * @time: 2020/11/7 15:16
 */

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/weixin/")
public class WXController {


    private WxMpService wxMpService;

    @AnonymousAccess
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        //访问：https://env.lichengjfzx.com/api/weixin/authorize?returnUrl=https://env.lichengjfzx.com

        //访问：http://127.0.0.1:8080/sell/wechat/authorize?returnUrl=http://www.imooc.com
        //若用注解@RestController（会自动解析成json）
        //返回：redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx085c556cb1d22b1f&redirect_uri=http%3A%2F%2Ft238997p11.qicp.vip%2Fsell%2Fwechat%2FuserInfo&response_type=code&scope=snsapi_userinfo&state=http%3A%2F%2Fwww.imooc.com&connect_redirect=1#wechat_redirect
        //若用注解@Controller
        //返回：直接重定向，请在微信打开，访问http://t238997p11.qicp.vip/sell/wechat/authorize?returnUrl=http://www.imooc.com，在微信打开后会跳转到returnUrl，即http://www.imooc.com

        //配置(配置已经完成)
        //回调方法
        String url = "https://env.lichengjfzx.com/api/weixin/userInfo";
        //构造网页授权url
        //可使用WxConsts.OAuth2Scope.SNSAPI_USERINFO模式，也可使用WxConsts.OAuth2Scope.SNSAPI_BASE模式，SNSAPI_BASE模式用户是无感知的
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("微信网页授权获取code，redirectUrl={}",redirectUrl);
        return "redirect:" + redirectUrl;
    }
    @AnonymousAccess
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,@RequestParam("state") String returnUrl){
        //获得access token
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("[微信网页授权] {}",e.getError());
            throw new RuntimeException(e.getError().getErrorMsg());
        }
        //获取openid
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("userInfo");
        return "redirect:" + returnUrl+"?openid=" + openId;
    }

}
